package com.quectel.core.module.dept.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.dept.DeptPersonAccessResourceConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dao.DeptPersonAccessResourceDao;
import com.quectel.core.module.dept.dto.DeptPersonAccessResourceDto;
import com.quectel.core.module.dept.entity.DeptPersonAccessResourceEntity;
import com.quectel.core.module.dept.service.DeptPersonAccessResourceService;
import com.quectel.core.module.dept.service.DeptPersonRoleResourceService;
import com.quectel.core.module.dept.service.DeptPersonRoleService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/07/27 10:30
 */
@DubboService
public class DeptPersonAccessResourceServiceImpl implements DeptPersonAccessResourceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeptPersonAccessResourceServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEPT_PERSON_ACCESS_RESOURCE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEPT_PERSON_ACCESS_RESOURCE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<DeptPersonAccessResourceDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(DEPT_PERSON_ACCESS_RESOURCE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private DeptPersonAccessResourceDao deptPersonAccessResourceDao;
    @Autowired
    private DeptPersonRoleService deptPersonRoleService;
    @Autowired
    private DeptPersonRoleResourceService deptPersonRoleResourceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleResourcesOptionalChanged(DeptPersonAccessResourceDto dto) {
        //查询数据库
        DeptPersonAccessResourceDto dbDto = selectById(dto.getId());
        if (dbDto != null && !dbDto.getOptional().equals(dto.getOptional())) {
            Map<String, Object> params = new HashMap<>();
            //修改为必选资源
            if (DeptPersonAccessResourceConstants.REQUIRED_RESOURCE.equals(dto.getOptional())) {
                //查询所有的角色 删除资源和角色关系
                deptPersonRoleResourceService.deleteByResourceId(dto.getId());
            }
        }
    }


    @Override
    public List<DeptPersonAccessResourceDto> queryAllAvailableResource() {
        List<DeptPersonAccessResourceEntity> entities = deptPersonAccessResourceDao.selectList(
                new LambdaQueryWrapper<DeptPersonAccessResourceEntity>()
                        .eq(DeptPersonAccessResourceEntity::getStatus, SystemConstants.NORMAL)

        );
        return CopyUtils.copyList(entities, DeptPersonAccessResourceDto.class);
    }

    @Override
    public DeptPersonAccessResourceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEPT_PERSON_ACCESS_RESOURCE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DeptPersonAccessResourceDto selectById(Long id) {
        DeptPersonAccessResourceEntity entity = deptPersonAccessResourceDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, DeptPersonAccessResourceDto.class));
    }

    @Override
    public List<DeptPersonAccessResourceDto> queryList(Map<String, Object> params) {
        List<DeptPersonAccessResourceEntity> list = deptPersonAccessResourceDao.queryList(params);
        List<DeptPersonAccessResourceDto> result = CopyUtils.copyList(list, DeptPersonAccessResourceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private DeptPersonAccessResourceDto paddingField(DeptPersonAccessResourceDto dto) {
        if (dto != null) {

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return deptPersonAccessResourceDao.queryTotal(params);
    }

    @Override
    public Long save(DeptPersonAccessResourceDto dto) {
        DeptPersonAccessResourceEntity entity = CopyUtils.copyObj(dto, DeptPersonAccessResourceEntity.class);
        entity.setId(Snowflake.nextId());
        deptPersonAccessResourceDao.insert(entity);
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DeptPersonAccessResourceDto dto) {
        DeptPersonAccessResourceEntity entity = CopyUtils.copyObj(dto, DeptPersonAccessResourceEntity.class);

        handleResourcesOptionalChanged(dto);
        deptPersonAccessResourceDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAllColumnById(DeptPersonAccessResourceDto dto) {
        DeptPersonAccessResourceEntity entity = CopyUtils.copyObj(dto, DeptPersonAccessResourceEntity.class);


        handleResourcesOptionalChanged(dto);

        MyBatisPlusUtils.updateAllColumnById(entity, deptPersonAccessResourceDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        deptPersonAccessResourceDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
